package ltd.hxya.novel.common.config;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class ThreadPoolConfig {
    //TODO 将线程池的配置信息放到配置类中

    @Value("${novel.thread.core-pool-size}")
    private Integer corePoolSize;

    @Value("${novel.thread.maximum-pool-size}")
    private Integer maximumPoolSize;

    @Value("${novel.thread.keep-alive-time}")
    private Integer keepAliveTime;

    @Value("${novel.thread.capacity}")
    private Integer capacity;

    @Bean
    public ThreadPoolExecutor threadPoolExecutor(){
        corePoolSize=corePoolSize==null?20:corePoolSize;
        maximumPoolSize=maximumPoolSize==null?100:maximumPoolSize;
        keepAliveTime=keepAliveTime==null?20:keepAliveTime;
        capacity=capacity==null?20:capacity;
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(capacity),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolExecutor;
    }
}
